package com.weituotian.system.service.impl;

import com.weituotian.core.jpa.domain.SimpleDtoMapper;
import com.weituotian.core.jpa.domain.Specification;
import com.weituotian.core.utils.DtoUtils;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.moudle.common.service.impl.BaseService;
import com.weituotian.system.dao.IBaseDao;
import com.weituotian.system.service.IAdminBaseService;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * 基础服务
 * Created by ange on 2016/9/26.
 */
@Transactional
public abstract class AdminBaseService<T, PK extends Serializable> extends BaseService<T,PK> implements IAdminBaseService<T, PK> {

    /**
     * 用于dao的findpage方法时候的查询条件
     *
     * @param pageInfo
     * @return
     */
    public abstract Specification<T> pageSpecification(PageInfo<?> pageInfo);

    public <V> T addByDto(V vo, PK id) {
        IBaseDao<T, PK> baseDao = getBaseDao();

        T entity = baseDao.findOne(id);

        DtoUtils.copyProperties(vo, entity);

        baseDao.persist(entity);

        return entity;
    }

    public void findPage(PageInfo<T> pageInfo) {

        if (pageInfo.getOrderby() == null) {
            pageInfo.addSort("id", "desc");//默认id倒序排列
        }

        List<T> content = getBaseDao().findPage(pageSpecification(pageInfo), pageInfo);
        pageInfo.setList(content);
    }

    public <V> void findPageVo(Class<V> voClazz, PageInfo<V> pageInfo, SimpleDtoMapper<T, V> mapper) {
        if (pageInfo.getOrderby() == null) {
            pageInfo.addSort("id", "desc");//默认id倒序排列
        }
        List<T> content = getBaseDao().findPage(pageSpecification(pageInfo), pageInfo);

        //转换成vo
        List<V> newList;
        if (mapper != null) {
            //使用mapper转换
            newList = (List<V>) mapper.toListDto(content);
        } else {
            newList = (List<V>) DtoUtils.defaultToListDto(voClazz, content);

            //默认转换方法
            /*newList = new ArrayList<V>();
            for (T t : content) {
                V vo = voClazz.newInstance();
                DtoUtils.copyProperties(t, vo);
                newList.add(vo);
            }*/

        }
        pageInfo.setList(newList);
    }

}
